package folder

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"gitee.com/ispace/core/infrastructure/common/dto"
)

type FolderBatchCreateHandler struct {
	request dto.WsRequestDto
}

type param struct {
	basePath string   `json:"basePath"`
	paths    []string `json:"paths"`
}

// Init 方法实现
func (h *FolderBatchCreateHandler) Init(request dto.WsRequestDto) {
	h.request = request
}

// Execute 方法实现
func (h *FolderBatchCreateHandler) Execute() dto.WsResponseDto {

	// step init:
	result := dto.WsResponseDto{}
	result.Header.Id = h.request.Header.Id

	// step 1: params
	bodyBytes, err := json.Marshal(h.request.Body)
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error marshalling message:%s", err)
		return result
	}

	params := param{}
	err = json.Unmarshal(bodyBytes, &params)
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error unmarshalling message:%s", err)
		return result
	}

	// step 2:
	err = h.batchCreate(params.basePath, params.paths)
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error CreateFile message:%s", err)
		return result
	}
	// step end:
	result.Header.Stat = 200
	return result
}

// 新增
func (fh *FolderBatchCreateHandler) batchCreate(basePath string, paths []string) error {

	for _, path := range paths {
		// 构建完整的文件夹路径
		fullPath := filepath.Join(basePath, path)
		// 创建文件夹
		err := os.MkdirAll(fullPath, os.ModePerm)
		if err != nil {
			return fmt.Errorf("failed to create folder at %s: %w", fullPath, err)
		}
	}
	return nil
}
